package sfy.md.netty.netty;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@ChannelHandler.Sharable                                       //#1
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx,
                            Object msg) {
        //从chanel拿到的数据但是没有进行处理
        System.out.println("Server received: "+"当前线程："+Thread.currentThread().getName() + msg);

        //对拿到的数据进行处理
        try {
            ByteBuf buf = (ByteBuf)msg;
//创建目标大小的数组
            byte[] barray = new byte[buf.readableBytes()];
//把数据从bytebuf转移到byte[]
            buf.getBytes(0,barray);
            //将byte[]转成字符串用于打印
            String str=new String(barray);

            if (str.length()>0)
            {
                System.out.println(str);
                System.out.flush();
            }
            else
            {
                System.out.println("不能读啊");
            }
           // buf.release();
        }finally {
          //   buf.release();
        }


        //将接收到的消息写回.注意,这个还没有"flush"消息给远程端.
        ctx.write(msg);                                        //#2
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // Flush所有之前写入的消息(挂起中)到远程端,然后在操作完成后关闭通道.
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);      //#3
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //记录异常
        cause.printStackTrace();                                //#4
        //关闭通道
        ctx.close();                                            //#5
    }
}


